package com.wmh.baseservice.common.shiro.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdInfo;
import com.wmh.baseservice.admin.service.AdInfoService;
import com.wmh.baseservice.common.config.KeyConfig;
import com.wmh.baseservice.common.utils.ShiroMd5Util;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsInfoService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

import javax.annotation.Resource;

/**
 * @author xy
 * @Date: 2021-10-20 15:21
 * @describe 自定义密码比较器
 */
public class PasswordMatcher extends SimpleCredentialsMatcher {

   @Resource
    private AdInfoService adInfoService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String password = info.getCredentials().toString();
        String[] users = info.getPrincipals().toString().split(":");
        String userName = users[0];
        String rawPassword = users[1];
        if (userName.contains(ShiroConfig.SHIRO_ADMIN)) {
            AdInfo adInfo = adInfoService.getOneForUpdate(new QueryWrapper<AdInfo>().eq(AdInfo.ACCOUNT, userName.replace(ShiroConfig.SHIRO_ADMIN, "")));
            return ShiroMd5Util.decodePwd(password, rawPassword + KeyConfig.SHIRO_SALE, adInfo.getSalt());
        } else if (userName.contains(ShiroConfig.SHIRO_SSO)) {
            //单点登录情况下直接放行
            return true;
        }else if(userName.contains(ShiroConfig.SHIRO_USER)){
            UsInfo usInfo = usInfoService.getOneForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.PHONE, userName.replace(ShiroConfig.SHIRO_USER, "")));
            return ShiroMd5Util.decodePwd(password, rawPassword + KeyConfig.SHIRO_SALE, usInfo.getSalt());
        }else if(userName.contains(ShiroConfig.SHIRO_MERCHANT)){
            MerchantInfo merchantInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.ACCOUNT, userName.replace(ShiroConfig.SHIRO_MERCHANT, "")));
            return ShiroMd5Util.decodePwd(password, rawPassword + KeyConfig.SHIRO_SALE, merchantInfo.getSalt());
        }
        return false;
    }

}
